//
//  PageScrollView.swift
//  SwiftProject
//
//  Created by wwj on 16/2/25.
//  Copyright © 2016年 wwj. All rights reserved.
//

import UIKit
import Kingfisher

class PageScrollView: UIView {
    private var scrollView: UIScrollView!
    private var pageControl: UIPageControl!
    private let MAXCOUNT = 3
    private var timer: NSTimer!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addScrollView()
        addTimer()
        addPageControl()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:添加ScrollerView
    private func addScrollView(){
        scrollView = UIScrollView()
        scrollView.pagingEnabled = true
        scrollView.delegate = self
        scrollView.bounces = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        
        for (var index = 0; index < MAXCOUNT; index++) {
            let imageView = UIImageView()
            imageView.tag = index
            scrollView.addSubview(imageView)
        }
        self.addSubview(scrollView)
    }
    
    private func addPageControl(){
        pageControl = UIPageControl()
        pageControl.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "v2_home_cycle_dot_normal")!)
        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "v2_home_cycle_dot_selected")!)
        pageControl.numberOfPages = 4
        self.addSubview(pageControl)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        scrollView.frame = self.bounds
        scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * CGFloat(MAXCOUNT), 0)
        let pageW: CGFloat = 80
        let pageH: CGFloat = 20
        let pageX: CGFloat = scrollView.frame.size.width - pageW
        let pageY: CGFloat = scrollView.frame.size.height - pageH
        pageControl.frame = CGRectMake(pageX, pageY, pageW, pageH)
        for(var index = 0; index < MAXCOUNT; index++){
            let imageView = scrollView.subviews[index] as! UIImageView
            if index == 0{
                imageView.backgroundColor = UIColor.blueColor()
            }else if index == 1{
                imageView.backgroundColor = UIColor.greenColor()
            }else if index == 2{
                imageView.backgroundColor = UIColor.yellowColor()
            }
            imageView.frame = CGRectMake(CGFloat(index) * scrollView.frame.size.width , 0, scrollView.frame.size.width, scrollView.frame.size.height)
        }
        updatePageScrollView()
    }
    
    private func addTimer(){
        timer = NSTimer(timeInterval: 3.0, target: self, selector: Selector("startTime"), userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
    }
    
    func startTime(){
        scrollView.setContentOffset(CGPointMake(scrollView.frame.size.width * 2.0 , 0), animated: true)
    }
    
    private func relaceTime(){
        timer.invalidate()
        timer = nil
    }
    
    //MARK: 更新内容
    private func updatePageScrollView() {
        for var i = 0; i < scrollView.subviews.count; i++ {
            let imageView = scrollView.subviews[i] as! UIImageView
            var index = pageControl.currentPage
            
            if i == 0 {
                index--
            } else if 2 == i {
                index++
            }
            
            if index < 0 {
                index = self.pageControl.numberOfPages - 1
            } else if index >= pageControl.numberOfPages {
                index = 0
            }
            
            imageView.tag = index
            imageView.kf_setImageWithURL(NSURL(string: "http://img1.imgtn.bdimg.com/it/u=1825165654,1935296637&fm=206&gp=0.jpg")!, placeholderImage: UIImage(named: "v2_placeholder_full_size"))
        }
        
        scrollView.contentOffset = CGPointMake(scrollView.frame.size.width, 0)
    }
}

extension PageScrollView: UIScrollViewDelegate{
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        var page: Int = 0
        var minDistance: CGFloat = CGFloat(MAXFLOAT)
        for i in 0..<scrollView.subviews.count {
            let imageView = scrollView.subviews[i] as! UIImageView
            let distance:CGFloat = abs(imageView.frame.origin.x - scrollView.contentOffset.x)
            
            if distance < minDistance {
                minDistance = distance
                page = imageView.tag
            }
        }
        pageControl.currentPage = page
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        relaceTime()
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        addTimer()
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        updatePageScrollView()
    }
    
    func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
        updatePageScrollView()
    }
    
}
